package com.team5101.encode;

import com.team5101.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;


/**
 * 自定义RPC解码器
 */
public class RpcDecoder extends ByteToMessageDecoder {


    private Class<?> clazz;

    private Serializer serializer;


    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {

        //在byteBuf缓冲区中标记当前的索引
        byteBuf.markReaderIndex();
        //在当前索引处获取
        int length = byteBuf.readableBytes();

        //创建一个初始化字节数据
        byte[] msg = new byte[length];

        //从当前{@code readerIndex}开始将该缓冲区的数据传输到指定的目标，并通过传输的字节数（= {@code dst.length}）增加{@code readerIndex}
        byteBuf.readBytes(msg, byteBuf.readerIndex(), length);

        //反序列化
        list.add(serializer.deserialize(clazz, msg));


    }


}
